<template>
  <div class="wechat-publicueditorsource-Add views-container">
    <choose-files
      ref="chooseFiles"
      :config="chooseFilesConfig"
      :changeEvt="chooseFilesChange"
    ></choose-files>
    <section class="flex-row flex-justify-b flex-warp form-group">
      <div
        class="wlm-form"
        style="flex-grow:1;margin-right:20px;"
      >
        <div class="wlm-form-header">图文素材</div>
        <div class="wlm-form-content">
          <el-form
            ref="sourceAdd"
            :model="formFormatData.formData"
            :rules="formFormatData.rules"
            size="small"
            label-width="120px"
            class="retail-form"
            label-position="right"
          >
            <el-form-item
              label=""
              v-for="(newsItem, newsIndex) in formFormatData.formData.news"
              v-if="currentItems === newsIndex"
              :key="newsIndex"
            >
              <el-form-item
                label="标题"
                :prop="'news.' + newsIndex + '.title'"
                :rules="{required: true, message: '请输入标题', trigger: 'blur'}"
              >
                <el-input v-model="newsItem.title">
                </el-input>
              </el-form-item>
              <el-form-item
                label="作者"
                :prop="'news.' + newsIndex + '.author'"
                :rules="{required: true, message: '请输入作者', trigger: 'blur'}"
              >
                <el-input v-model="newsItem.author">
                </el-input>
              </el-form-item>
              <el-form-item
                label="正文"
                :prop="'news.' + newsIndex + '.content'"
                :rules="{required: true, message: '请输入正文', trigger: 'blur'}"
              >
                <ueditor
                  :ueditorChange="infoChange"
                  :defaultMsg='newsItem.content'
                  :config='{initialFrameWidth: null,initialFrameHeight: 350}'
                  ref="ue"
                ></ueditor>
              </el-form-item>
              <el-form-item label="原文链接">
                <el-input v-model="newsItem.content_source_url">
                </el-input>
                <div class="form-help">（非必填项）</div>
              </el-form-item>
              <el-form-item
                label="封面图"
                prop="thumbCover"
              >
                <img
                  @click="$refs.chooseFiles.toggle()"
                  class="wlm-upload-img"
                  style="cursor: pointer;"
                  :src="`${getPath(newsItem.thumb_url||'default_picture.png')}`"
                >
                <div class="form-help">封面大图片建议图片长宽比：2.35:1</div>
              </el-form-item>
              <el-form-item
                label="摘要"
                :prop="'news.' + newsIndex + '.digest'"
                :rules="{required: true, message: '请输入摘要', trigger: 'blur'}"
              >
                <el-input
                  type="textarea"
                  style="width:75%;"
                  :autosize="{ minRows: 4, maxRows: 8}"
                  placeholder="请输入内容"
                  v-model="newsItem.digest"
                >
                </el-input>
              </el-form-item>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <div class="wlm-form">
        <div class="wlm-form-header">图文列表</div>
        <div class="wlm-form-content">
          <el-form
            size="small"
            label-width="120px"
            class="retail-form"
            label-position="right"
          >
            <div class="news-list">
              <div
                class="first-news"
                :class="{'active':currentItems === 0}"
                @click="currentItems = 0"
              >
                <img :src="`${formFormatData.formData.news[0]['thumb_url']?formFormatData.formData.news[0]['thumb_url']:getPath('default_picture.png')}`">
                <p class="news-title">{{formFormatData.formData.news[0]['title']}}</p>
                <div class="bg"></div>
              </div>
              <div
                v-for="(newsItem, newsIndex) in formFormatData.formData.news"
                v-if="newsIndex > 0"
                :key="newsIndex"
                class="news clearfix"
                :class="{'active':newsIndex === currentItems}"
                @click="currentItems = newsIndex"
              >
                <img :src="`${newsItem['thumb_url']?newsItem['thumb_url']:getPath('default_picture.png')}`">
                <p class="news-title">{{newsItem.title}}</p> <i
                  class="el-icon-close close-btn"
                  @click="delParameter(newsIndex)"
                ></i>
              </div>
              <div
                class="add-news"
                @click="addParameter"
              >+</div>
            </div>
          </el-form>

        </div>
      </div>
    </section>

    <div
      v-cloak
      class="wlm-fixed-btn flex-row flex-align-c flex-justify-c"
    >
      <el-button
        size="small"
        @click="saveForm('')"
        :disabled="isFormFormatSave"
        :loading="isFormFormatSave"
        type="primary"
      >保存</el-button>
      <el-button
        size="small"
        :disabled="isFormFormatSave"
        :loading="isFormFormatSave"
        @click="saveForm('wechat')"
        type="primary"
      >保存并上传至微信服务器</el-button>
      <router-link
        tag="span"
        to="/channel/weChatPublicUeditorSource"
      >
        <el-button
          size="small"
          :disabled="isFormFormatSave"
          :loading="isFormFormatSave"
        >返回</el-button>
      </router-link>
    </div>
  </div>
</template>

<script>
import ChooseFiles from '@/components/ChooseFiles/index'
import ueditor from '@/components/Ueditor/index'
import {
  getMaterial,
  upload2WechatByFileID,
  addMaterialNews
} from '@/api/channel'
import mixins from '@/mixins/mixins'
export default {
  mixins: [mixins.getters('Form')],
  name: 'ManagementUserAdd',
  components: {
    ueditor,
    ChooseFiles
  },
  computed: {
    getPath() {
      return function(path) {
        return (path.includes('https://') || path.includes('http://')) ? `${path}` : require(`@/assets/custorm_style/${path}`)
      }
    }
  },
  directives: {

  },
  data() {
    var checkUploadCover = (rule, value, callback) => {
      const { message } = rule
      const currentCover = this.formFormatData.formData.news[this.currentItems]['thumb_url']
      if (!currentCover) {
        return callback(new Error(`${message}！~`))
      } else {
        callback()
      }
    }

    return {
      currentItems: 0,
      chooseFilesConfig: {
        type: ['image'],
        model: 'normal',
        initList: [],
        file_type: 'image',
        uploadConfig: {
          params: {
            mode: 'perm'
          }
        }
      },
      formFormatData: {
        key: 'sourceAdd',
        api: {
          editForm: {
            api: getMaterial,
            params: {
              attach_id: ''
            },
            redirect: 'attach_id'
          },
          submitForm: addMaterialNews
        },
        formData: {
          target: '',
          news: [{
            title: '',
            thumb_url: '',
            content_source_url: '',
            author: '',
            digest: '',
            content: '',
            show_cover_pic: ''
          }]
        },
        rules: {
          thumbCover: [
            {
              message: '请上传封面图',
              required: true,
              validator: checkUploadCover,
              trigger: 'change'
            }
          ]
        }
      }
    }
  },
  methods: {
    saveForm(isTarget = '') {
      this.formFormatData.formData.target = isTarget
      this.formFormatSubmit({ router: { type: 'replace', path: '/channel/weChatPublicUeditorSource', code: 1 } })
      // const news = this.formFormatData.formData.news
      // let hasThumb = true
      // news.map(item => {
      //   const { thumb_url: [{ file_path }] } = item
      //   if (!file_path) {
      //     hasThumb = false
      //   }
      // })

      // if (hasThumb) {
      //   this.formFormatData.formData.target = isTarget

      // } else {
      //   this.$message.error('请上传素材图片')
      // }
    },
    chooseFilesChange({ currentRow, displayData }) {
      if (displayData.length > 0) {
        const { file_path } = displayData[displayData.length - 1]
        this.formFormatData.formData.news[this.currentItems]['thumb_url'] = file_path
        upload2WechatByFileID({ ids: currentRow, mode: 'perm' }).then(res => {
          this.getTableList()
        })
      }
    },
    addParameter() {
      this.formFormatData.formData.news.push({ title: '', thumb_url: '', content_source_url_status: '0', content_source_url: '', author: '', digest: '', content: '', show_cover_pic: '' })
    },
    delParameter($index) {
      this.formFormatData.formData.news.splice($index, 1)
    },
    infoChange(msg, isReady) {
      if (isReady) {
        this.formFormatData.formData.news[this.currentItems]['content'] = msg
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.wechat-publicueditorsource-Add {
  .news-list {
    .first-news {
      width: 256px;
      padding: 12px;
      border: 1px solid #eee;
      position: relative;
      height: 149px;
      overflow: hidden;
      cursor: pointer;
      &.active {
        border: 2px solid #fb6638;
      }
      img {
        display: inline-block;
        vertical-align: middle;
        min-width: 100%;
        min-height: 100%;
        max-width: 100%;
        max-height: 100%;
        border-radius: 4px;
      }
      .news-title {
        position: absolute;
        bottom: 24px;
        left: 24px;
        right: 24px;
        color: #fff;
        line-height: 12px;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        z-index: 5;
      }
      .bg {
        background: -webkit-gradient(
          linear,
          left top,
          left bottom,
          from(rgba(0, 0, 0, 0)),
          to(rgba(0, 0, 0, 0.5))
        );
        background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.5));
        right: 12px;
        height: 40px;
        position: absolute;
        bottom: 12px;
        left: 12px;
      }
    }
    .news {
      height: 82px;
      padding: 12px;
      border: 1px solid #eee;
      border-top-color: #fff;
      position: relative;
      cursor: pointer;
      img {
        float: right;
        width: 60px;
        height: 60px;
      }
      .news-title {
          float: left;
          width: auto;
          height: 58px;
          line-height: 58px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          color: #333;
      }
    }
    .news .close-btn {
      display: none;
    }
    .news.active {
      border: 2px solid #fb6638;
      padding: 11px;
      height: 82px;
      position: relative;
      .news-title {
        float: left;
        width: 170px;
        height: 58px;
        line-height: 58px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #333;
      }
      .close-btn {
        position: absolute;
        top: -5px;
        right: -5px;
        font-size: 14px;
        color: #fb6638;
        cursor: pointer;
        border-radius: 50%;
        background: #fb6638;
        color: #fff;
      }
    }
    .add-news {
      cursor: pointer;
      height: 82px;
      padding: 12px;
      border: 1px dashed #eee;
      border-top-color: #fff;
      line-height: 58px;
      text-align: center;
      font-size: 30px;
      color: #bbb;
    }
  }
}
</style>
